package com.foo.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.foo.common.json.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.foo.common.config.Global;
import com.foo.common.utils.http.HttpUtils;

import java.util.HashMap;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "https://qifu-api.baidubce.com/ip/local/geo/v1/district";

    public static String getRealAddressByIP(String ip)
    {
        String address = "XX XX";

        if (Global.isAddressEnabled())
        {
            String rspStr = HttpUtils.sendRequest(IP_URL, new JSONObject().fluentPut("ip", ip), new HashMap<>(), "GET");
            JSONObject jsonObject = JSONObject.parseObject(rspStr);
            if (StringUtils.isEmpty(rspStr))
            {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            try
            {
                String region = jsonObject.getJSONObject("data").getString("prov");
                String city = jsonObject.getJSONObject("data").getString("city");
                address = region + " " + city;
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }
}
